<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/7/1 15:00
 * Modified Time: 2019/7/1 15:00
 * Version: 2.0
 */

namespace App\Modules\MemberCard\Criterias;


use Flower\Core\Repository\Contracts\CriteriaInterface;
use Flower\Core\Repository\Contracts\RepositoryInterface;

class AppGetCardTypeListCriteria implements CriteriaInterface
{
    private $store_id;
    private $status;
    private $keywords;

    public function __construct($store_id, $status, $keywords)
    {
        $this->store_id = $store_id;
        $this->status = $status;
        $this->keywords = $keywords;
    }

    public function apply($model, RepositoryInterface $repository)
    {
        $store_id = $this->store_id;
        $status = $this->status;
        $keywords = $this->keywords;


        $model = $model->select([
            'id',
            'name',
            'category',
            'price',
            'count',
            'present',
            'status',
            'discount_way',
            'royalty',
            'created_at',
            'skin'
        ])
            ->when($keywords!==null, function ($query) use ($keywords) {
                $query->where('name', 'like', '%' . $keywords . '%');
            })
            ->with(['cardTypeService' => function ($query) {
                $query->with(['service']);
            }])
            ->when($status != 2, function ($query) use ($status) {
                $query->where('status', $status);
            })
            ->withCount(['memberCard'])
            ->where('store_id', $store_id)
            ->orderBy('status', 'DESC')
            ->orderBy('id', 'DESC');

        return $model;
    }
}